package com.example.shopp_2301.xq

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.widget.Button
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.base.mvvm.BaseActivity
import com.example.shopp_2301.R
import com.example.shopp_2301.adapter.CommentApdater
import com.example.shopp_2301.adapter.TuijianAdapter
import com.example.shopp_2301.databinding.ActivityXqBinding
import com.example.shopp_2301.utils.GlideUtils
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.youth.banner.loader.ImageLoader


@Route(path = "/app/XqActivity")
class XqActivity : BaseActivity<ActivityXqBinding,XqViewModel>() {
    @Autowired
    @JvmField
    var goodsId:Int = 1

    val imgs = mutableListOf<String>()//存放轮播图图片

    lateinit var tuijianAdapter: TuijianAdapter
    //定义一个属性id的全局变量，当商品加载出来后给他赋值
    lateinit var attrId:String
    lateinit var imgpath:String

    lateinit var commentApdater: CommentApdater
    @SuppressLint("MissingInflatedId")
    override fun initView() {
        ARouter.getInstance().inject(this)
        //请求详情页数据
        viewModel.xq(goodsId,"normal")
        //点击返回
        binding.ivBack.setOnClickListener {
            finish()
        }
        //点击加入购物车
        //热门推荐
        tuijianAdapter = TuijianAdapter()
        binding.rvTuijian.adapter = tuijianAdapter
        binding.rvTuijian.layoutManager = GridLayoutManager(this,2,GridLayoutManager.HORIZONTAL,false)
        viewModel.tuijian(10,1)
        //popupmenu菜单
        binding.ivMore.setOnClickListener {
            val popupMenu = PopupMenu(this@XqActivity,it)
            popupMenu.inflate(R.menu.pop_menu)
            popupMenu.setOnMenuItemClickListener {
                when(it.itemId){
                    R.id.index -> ARouter.getInstance().build("/app/ShopActivity").withInt("position",0).navigation()
                    R.id.car -> ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
                    R.id.mine -> ARouter.getInstance().build("/app/ShopActivity").withInt("position",3).navigation()
                }
                return@setOnMenuItemClickListener false
            }
            popupMenu.show()
        }
        //点击加入购物车，实现添加数据
        binding.tvAddCar.setOnClickListener {
            viewModel.addCar(1,attrId,goodsId)
        }
        //点击购物车，跳转到购物车页面
        binding.tvGoCar.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
        }
        binding.ivGoCar.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("position",2).navigation()
        }

        //点击分享图标，弹出对话框，显示二维码  ，点击确定，弹出分享框 点击取消，什么也不做
        binding.ivShare.setOnClickListener {
            val inflate = LayoutInflater.from(this).inflate(R.layout.item_share, null)
            val alertDialog = AlertDialog.Builder(this)
                .setTitle("提示")
                .setView(inflate)
                .create()
            //生成二维码
            val bitmap =
                BarcodeEncoder().encodeBitmap(goodsId.toString(), BarcodeFormat.QR_CODE, 200, 200)
            inflate.findViewById<ImageView>(R.id.iv).setImageBitmap(bitmap)

            inflate.findViewById<Button>(R.id.yes).setOnClickListener {
                //对话框消失
                alertDialog.dismiss()
                //显示分享框
                val web: UMWeb = UMWeb("http://www.baidu.com")
                web.title = "This is music title" //标题
                val image: UMImage = UMImage(this, R.mipmap.ic_launcher) //资源文件
                web.setThumb(image) //缩略图
                web.description = "my description" //描述
                ShareAction(this)
                    .withMedia(web)
                    .setDisplayList(SHARE_MEDIA.QQ)
                    .setCallback(object :UMShareListener{
                        override fun onStart(p0: SHARE_MEDIA?) {

                        }

                        override fun onResult(p0: SHARE_MEDIA?) {

                        }

                        override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                            ToastUtils.showLong(p1?.message)
                        }

                        override fun onCancel(p0: SHARE_MEDIA?) {

                        }
                    })
                    .open()
            }
            inflate.findViewById<TextView>(R.id.no).setOnClickListener {
                alertDialog.dismiss()
            }
            alertDialog.show()
        }

        //初始化评论
        commentApdater = CommentApdater()
        binding.rvComment.adapter = commentApdater
        binding.rvComment.layoutManager = LinearLayoutManager(this)

        viewModel.comment(goodsId,10,1,"0")
    }

    override fun initData() {
        //观察结果
        viewModel.xqSuccess.observe(this){
            if(it.code==200){
                binding.info = it.data.productInfo
                attrId = it.data.productValue.values.toList()[0].id.toString()//获取商品属性的第一个的id
                imgpath = it.data.productInfo.image//设置图片网址，动画使用
                //展示轮播图
                imgs.add(it.data.productInfo.image)
                imgs.add(it.data.productInfo.image)
                binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null&&imageView!=null) {
                                Glide.with(context).load(path).into(imageView)
                            }
                        }
                    })
                    .start()
                //显示已选择的规格
                binding.tvSelected.text= "已选择：${it.data.productValue.keys.toList().get(0)}"
            }else{
                ToastUtils.showLong("请求失败：${it.message}")
            }
        }
        viewModel.tjSuccess.observe(this){
            if(it.code==200){
                tuijianAdapter.data.clear()
                tuijianAdapter.data.addAll(it.data.list)
                tuijianAdapter.notifyDataSetChanged()
            }
        }
        //观察添加购物车的结果
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                //展示动画效果，从左上角飞到加入购物车内
                //创建一张图片
                val image = ImageView(this)
                //设置图片大小
                val layoutParams = LayoutParams(200, 200)
                image.layoutParams = layoutParams
                //给图片设置内容
                GlideUtils.loadImage(this,imgpath,image)
                //将图显示在总布局中
                binding.main.addView(image)
                //设置动画
                //获取屏幕宽度
                val width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()
                //从左边到右边然后回来一些
                val translationX =
                    ObjectAnimator.ofFloat(image, "translationX", 0f, width, width / 7 * 4)
                val translationY = ObjectAnimator.ofFloat(image, "translationY", 0f, height)

                val animatorSet = AnimatorSet()
                animatorSet.duration = 2000
                animatorSet.play(translationY).with(translationX)

                animatorSet.addListener(object :Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {

                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.main.removeView(image)
                    }

                    override fun onAnimationCancel(animation: Animator) {

                    }

                    override fun onAnimationRepeat(animation: Animator) {

                    }
                })

                animatorSet.start()//启动


            }
        }
        //观察评论内容
        viewModel.commentSuccess.observe(this){
            if(it.code==200){
                commentApdater.data.clear()
                commentApdater.data.addAll(it.data.list)
                commentApdater.notifyDataSetChanged()
            }
        }
    }

    override fun getViewModel(): Class<XqViewModel> {
        return XqViewModel::class.java
    }

    override fun getLayout(): Int {
        return R.layout.activity_xq
    }

}